package com.example.CarManagement.config.SecurityConfig;


import com.example.CarManagement.filter.JWTAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration // 配置类
@EnableMethodSecurity // 基于方法授权
public class WebSecurityConfig {
    /**
     * 自定义用户认证逻辑
     */
    @Autowired
    private UserDetailsService userDetailsService;


    @Autowired
    private JWTAuthenticationFilter jwtAuthenticationFilter;


    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 身份验证实现
     */
    @Bean
    public AuthenticationManager authenticationManager() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder);
        return new ProviderManager(daoAuthenticationProvider);
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {


        // 运行访问接口
        http.authorizeHttpRequests((requests) -> {
            // 对于登录login 注册register 验证码captchaImage 允许匿名访问
            requests.antMatchers("/sys/user/login").permitAll()
                    .antMatchers("/file/download").permitAll()
                    .antMatchers("/sys/user/wxLogin").permitAll()
                    .antMatchers("/sys/user/push").permitAll()
                    .antMatchers("/ws").permitAll()
                    .antMatchers("/ws/**").permitAll()

                    // 静态资源，可匿名访问
                    .antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll().antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**").permitAll()

                    // 除上面外的所有请求全部需要鉴权认证
                    .anyRequest().authenticated();

        });


        // 禁用form登录
        http.formLogin().disable();

//         添加jwt过滤器
        http.addFilterAt(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);


        http.exceptionHandling(exception -> {
            // 请求未登录处理
            exception.authenticationEntryPoint(new MyAuthenticationEntryPoint());
            // 用户没有权限处理
            exception.accessDeniedHandler(new MyAccessDeniedHandler());
        });


        // 跨域
        http.cors(Customizer.withDefaults());


        // 关闭csrf攻击防御
        http.csrf(csrf -> csrf.disable());
        return http.build();
    }


}
